package com.dimples.dd.security.core.exception;

import cn.hutool.core.util.StrUtil;
import com.dimples.dd.common.result.CommonResult;
import com.dimples.dd.common.result.ResultCode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 自定义 token 无效异常
 *
 * @author zhongyj <1126834403@qq.com><br/>
 * @date 2024/5/30
 */
@Component
public class DDAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
            throws IOException {
        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_OK);
        ObjectMapper mapper = new ObjectMapper();
        if (StrUtil.containsIgnoreCase(authException.getMessage(), "Jwt expired")) {
            mapper.writeValue(response.getOutputStream(), CommonResult.error(ResultCode.TOKEN_EXPIRED));
        } else {
            mapper.writeValue(response.getOutputStream(), CommonResult.error(ResultCode.TOKEN_INVALID));
        }
    }
}
